package com.yiguantong.police.ui.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
 * Created by Administrator on 2016-7-13.
 */
public class HttpUtil {

    //没有网络连接
    public static final String NETWORN_NONE = "无网络";
    //wifi连接
    public static final String NETWORN_WIFI = "WIFI";
    //数据流量
    public static final String NETWORN_MOBILE_FLOW = "GPRS";
    //其他
    public static final String NETWORN_OTHER = "其他";

    /**
     * 判断是否是wifi还是数据连接GPRS
     */
    public static String checkNetworkType(Context context) {
        try {
            ConnectivityManager mConnectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            //检查网络连接
            NetworkInfo info = mConnectivity.getActiveNetworkInfo();
            int netType = info.getType();
            isNetOk(context);
            if (info == null || !info.isAvailable()) {
                // 注意一：
                // NetworkInfo 为空或者不可以用的时候正常情况应该是当前没有可用网络，
                // 但是有些电信机器，仍可以正常联网，
                // 所以当成net网络处理依然尝试连接网络。
                // （然后在socket中捕捉异常，进行二次判断与用户提示）。
                return NETWORN_NONE;
            } else {
                // NetworkInfo不为null开始判断是网络类型
                netType = info.getType();
                if (netType == ConnectivityManager.TYPE_WIFI) {
                    // wifi net处理
                    return NETWORN_WIFI;
                } else if (netType == ConnectivityManager.TYPE_MOBILE) {
                    return NETWORN_MOBILE_FLOW;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return NETWORN_OTHER;
        }
        return NETWORN_OTHER;
    }

    /**
     * 是否wifi联网
     */
    public static boolean isWifiConnect(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
        if (isConnected) {
            boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;
            return isWiFi;
        } else {
            return false;
        }
    }

    /**
     * 判断是否有网
     */
    public static boolean isNetOk(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm != null) {
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            if (netInfo != null) {
                if (netInfo.isConnected()) {
                    return true;
                }
                return false;
            }
        }
        return false;
    }
}